<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
    <meta name="renderer" content="webkit" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
	<title>JS简单实现根据奖品权重计算中奖概率实现抽奖的方法</title>
	<link rel="stylesheet" href="./layui/css/layui.css" />
</head>
<body>
	
	<section class="layui-col-md10" style="margin: 0 auto; float: none;">
		<div class="layui-card">
			<div class="layui-card-header">JS 根据奖品权重计算中奖概率实现抽奖的方法</div>
			<div class="layui-card-body">
				<div>
					<blockquote class="layui-elem-quote"><span id="titlestr"></span></blockquote>
				</blockquote>			
				</div>		
				
				<div>
				
					<blockquote class="layui-elem-quote layui-quote-nm">		
						<p>本抽奖程序的奖项权重和值：<span id="weightSum">***</span></p>
					</blockquote>
					
					<blockquote class="layui-elem-quote layui-quote-nm">						
						<p>
							<span class="layui-word-aux">您本次抽奖产生的权重随机值：</span>
							<span id="weightRandom">***</span>
						</p>
						<p>
							<span class="layui-word-aux">您本次抽奖结果：</span>
							<span id="printData">***</span>
						</p>
						<p>							
							<span class="layui-word-aux">本次抽奖时间：</span>
							<span id="dateNow" class="layui-word-aux"></span>
						</p>
					</blockquote>			
				</div>
				
				<div id="action" class="text-center">
					<button type="button" name="btnSave" class="layui-btn" data-type="save">开始抽奖</button>				
					<button type="reset" name="btnReset" class="layui-btn layui-btn-primary" onclick="window.location.reload();">取消</button>
				</div>				
			</div>
		</div>		
	</section>
	<script type="text/javascript">
		function load(name) {
			let xhr = new XMLHttpRequest(),
				okStatus = document.location.protocol === "file:" ? 0 : 200;
				xhr.open('GET', name, false);
				xhr.overrideMimeType("text/html;charset=utf-8");//默认为utf-8
				xhr.send(null);
				return xhr.status === okStatus ? xhr.responseText : null;
		}
 
		let text = load("zzz.txt");
			document.getElementById("titlestr").innerHTML = text;	//输出本次抽奖结果
				
	</script>
	<!--recommended script position-->
	<script type="text/javascript" src="./layui/layui.js" charset="utf-8"></script>
	<script type="text/javascript">

		
 
		//layui 模块化引用
		layui.use(['jquery', 'util'], function(){
			var $ = layui.$, util = layui.util;
			var strArr =  layui.jquery.parseJSON(text);
			//设置奖项名称、权重、中奖次数等数组
			//var prizes = ["一等奖", "二等奖", "三等奖", "未中奖"];	//奖项名称数组
			//var prizeWeight = [1, 5, 20, 74];	//奖项权重数组，表征各奖项的中奖机会占总数的百分比。比如一等奖的中奖率是1%，二等奖的中奖率是5%			
			
			//开发者也可合并声明奖项名称、权重等数组在一个对象中
			var prizes = strArr;				
			
			// 数组累加求和函数：Array.reduce(prev ,cuurentValue)
			var weightSum = prizes.reduce(function(prev, currVal){	//计算权重之和：1+5+20+74=100
				return prev + currVal.weight;	//prev 是前一次累加后的数值，currVal 是本次待加的数值
			}, 0);
			document.getElementById("weightSum").innerHTML = weightSum;	//设置权重和值
			
			//抽奖函数
			var lottery = function(weightSum) {
				var res = "未中奖";	//默认设置抽奖结果为“未中奖”
				console.log("本程序的奖项权重和值：", weightSum);
				
				//生成一个权重随机数，介于1-100
				var random =  Math.floor(Math.random()*weightSum)+1;
				//生成一个权重随机数（0到1之间），再乘以权重和值（100），这样得到一个大于等于 0 且小于 100 的随机数
				console.log("本次抽奖的权重随机数：", random);
				var randomdata = {"name": "权重数", "weight": random,"type":2};
				var tempArr =  [];
				var cal = 0;
				 for(let i=0,l=prizes.length;i<l;i++) {
					cal  = cal + prizes[i].weight;
					tempArr.push({"name":prizes[i].name, "weight": cal});
					}

				tempArr.push(randomdata);
				//权重数组重组并排序
				var concatWeightArr = tempArr.concat(random);	//将随机数加入权重数组
				var sortedWeightArr = concatWeightArr.sort(function(a, b){
				if (a.weight==b.weight)
				{
					 if (a.type == 2)
					 {
						return -1;
					 }
					 else
					 {
						return 1;
					 }
				}
				return a.weight-b.weight;});	//将包含随机数的新权重数组按从小到大（升序）排序
				console.log("含权重随机数的新权重数组升序排序后：", sortedWeightArr);
				
				//索引权重随机数的数组下标
				var randomIndex = sortedWeightArr.indexOf(randomdata);	//索引随机数在新权重数组中的位置
				randomIndex = Math.min(randomIndex, prizes.length -1);	//权重随机数的下标不得超过奖项数组的长度-1，重新计算随机数在奖项数组中的索引位置				
				console.log("本次权重随机数对应的数组下标：", randomIndex);
				
				//取出对应奖项
				res = prizes[randomIndex];	//从奖项数组中取出本次抽奖结果
				console.log("本次抽奖结果：", res.name);
				
				return {"weightSum": weightSum , "weightRandom": random, prizeIndex: randomIndex, "data": res};	//返回本次抽奖结果
			};
			
			//注册按钮事件
            $('.layui-btn[data-type="save"]').on('click', function () {
                var res = lottery(weightSum);
				document.getElementById("dateNow").innerHTML = util.toDateString(new Date());	//输出本次抽奖时间
				document.getElementById("weightRandom").innerHTML = res.weightRandom;	//输出本次抽奖的权重随机数
				document.getElementById("printData").innerHTML = res.data.name;	//输出本次抽奖结果
			
            });
		});
	</script>
</body>
</html>
